package org.colswe.solestac.control;

import java.io.IOException;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.NoResultException;
import javax.persistence.NonUniqueResultException;
import org.colswe.solestac.dao.UserDao;
import org.colswe.solestac.entity.ActualUser;
import org.colswe.solestac.entity.FinalUser;

/**
 *
 * @author laaguelless
 *
 */
public class LoginControl {

    /***EntityManagerFactory created to manage the Persistenc Unit.
     */
    private static EntityManagerFactory emf = Persistence.createEntityManagerFactory("SOLESTACPU");
    /**LogControl object to record events in the log.
     */
    private LogControl log;
    
    /**Default constructor.
     */
    public LoginControl() {
        createLog();
    }
    
    /**Creation of the Log object to record events.
     */
    private void createLog() {
        try {
            this.log = new LogControl("com.colswe.solestac.LoginControl");
        } catch(IOException ex) {
            ex.printStackTrace(System.err);
        }
    }

    /** Validates user combination - password entered by the user.
     * Brings rolepermissions and initializes the User Session <p> Returns a List of
     * Perimmission_VO that contains the user's role permissions if the Login is
     * successful. Null otherwise.
     * @param name Username given by the login view @param password An String
     * @param password password entered by the user
     * that contains the password entered 
     * @return List<Permission_VO> 
     * @throws Exception if there is an error with the data base
     */
    public boolean login(final String name, final String password) throws Exception {
        EntityManager em = emf.createEntityManager();
        em.getTransaction().begin();
        final String username = name.toLowerCase();
        try {
            UserDao userDao = new UserDao();
            List<FinalUser> users = userDao.searchByUsername(username, em);
            FinalUser user = users.get(0);    
            
            if (verifyPassword(user, password)) {
                /** Initializes the ActualUser instance  */
                ActualUser acUser = ActualUser.getInstance();                
                acUser.setInstance(user.getName(), user.getRolId().getName(), user.getRolId().getPermissionList(), user.getId());
               return true;
            } else {
                return false;
            }
        } catch (NoResultException exp) {
            log.logging(exp);
            return false;
        } catch (NonUniqueResultException exp) {
            log.logging(exp);
            throw exp;
        } catch (Exception exp) {
            log.logging(exp);
            throw exp;
        } finally {
            em.close();
        }
    }

    /**Does logout.
     */
    public void logout() {
        ActualUser acuser = ActualUser.getInstance();
        acuser.setNull();
    }

    /**Verifies the password of the user with the password given in the login process.
     * @param user The user with the username given by the user.
     * @param password The password given by the user.
     * @return True if the password given matches with the password stored in the system.
     */
    private boolean verifyPassword(final FinalUser user, final String password) {
        return user.getPassword().equals(password);
    }
}
